# -*- coding: utf-8 -*-
"""
Module to handle markup rendering to html.

TODO:
 - code.css for code highlighting with bb-code/postmarkup
""" 
from django.utils.safestring import mark_safe
from django.utils.html import escape




CHOICES = [("plain", "plaintext (no markup, html will be escaped)")]
HANDLERS = {"plain":lambda t: "<pre class='plaintext'>%s</pre>" % escape(t), 
            "raw":lambda t: t}


# restructuredText

try:
    from docutils.core import publish_parts
    import rstdirective
    
    def rst_handler(text):
        settings = {
            'initial_header_level': 2,
            'doctitle_xform': False,
            'footnote_references': 'superscript',
            'trim_footnote_reference_space': True,
            'default_reference_context': 'view',
            'link_base': '',
            }
        parts = publish_parts(
        source=text,
        writer_name="html4css1",
        settings_overrides=settings
        )
        return parts['body']
    CHOICES.append(("rst", "reStructuredText"))
    HANDLERS["rst"] = rst_handler
except ImportError:
    pass


# markdown

try:
    import markdown
    md = markdown.Markdown(safe_mode="replace")
    CHOICES.append(("md", "Markdown"))
    HANDLERS["md"] = md.convert
except ImportError:
    pass

# bbCode

try:
    from postmarkup import render_bbcode
    CHOICES.append(("bb", "bb Code"))
    HANDLERS["bb"] = render_bbcode
except ImportError:
    pass


# textile

try:
    from textile import textile
    CHOICES.append(("tex", "textile"))
    HANDLERS["tex"] = textile
except ImportError:
    pass

# creole

try:
    from creole import creole2html
    CHOICES.append(("creo", "Creole"))
    HANDLERS["creo"] = creole2html
except ImportError:
    pass


ADMIN_CHOICES = CHOICES[:]
ADMIN_CHOICES.append(("raw", "raw html"),)


def render(text, markup):
    if markup not in HANDLERS:
        raise ValueError, "Hanlder %s not found! Valid handlers are: %s" % (
                            markup, ", ".join(HANDLERS.keys()))
    return mark_safe(HANDLERS[markup](text.replace("\t", " "*4)))



from docutils.parsers.rst import roles
from docutils import nodes, utils

from django.contrib.auth.models import User

from utils.templatetags.base_extras import userlink


def user_role(name, rawtext, text, lineno, inliner,
            options={}, content=[]):
    try:
        user = User.objects.get(username=text)
        retval = userlink(user)
    except User.DoesNotExist:
        retval = ("<span class='invalid_user_link' title='user \"%s\" "
                 + "not found'>%s</span>") % (text, text)
    print "retval: ", retval
    return [nodes.raw('', retval, format='html')],[]


                        
roles.register_canonical_role("user", user_role)
